define(function (require, exports, module) {
    /**--tmpl-require--**/
    require('jtemplate');
    require('jdialog');
    require("imagefit");

    require('jquery-validate');
    require('validate');
    require('v-addmethod');

    common = require('common');

    exports.upload = function (configs, id, boxid) {
        require('jupload');
        $("#" + id).JUpload({
            url: common.url("/admin/upload/upload"),  //后台上传路径
            max_filenum: 0,
            src: "src",
            datas: configs.datas,
            image_container: boxid,
            onSuccess: configs.onSuccess,
            onRemove: configs.onRemove,
        });

    }
    exports.ajaxResultByYu = function (url, data, callback, failback) {

        $.ajax({
            type: 'POST',
            url: url,
            data: data,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'json',

            success: function (thisData) {

                layer.closeAll("loading");

                if (thisData.code == '1') {
                    if ($.isFunction(failback)) {
                        failback(thisData);
                    } else {
                        layer.alert(thisData.message, {
                            icon: 2, timeout: 1800, end: function () {

                            }
                        });

                    }

                } else {
                    if ($.isFunction(callback)) {
                        callback(thisData);
                    } else {
                        layer.msg(thisData.message, {
                            icon: 1, timeout: 1800, end: function () {
                                location.reload(true);
                            }
                        });
                    }
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                layer.closeAll("loading");
                layer.alert("系统出了小差，请联系管理员！", {icon: 2});
            }
        });
    };

    exports.init = function () {
        require('editor');
        require("ajaxproxy");
        var common = require("common");

        var editor;
        editor = KindEditor.create('#editor-content', {
            uploadJson: common.url('/admin/upload/kindeditor_upload'),
            allowFileManager: true,
            afterBlur: function () {
                this.sync();
            }
        });
        //初始化AjaxProxy插件
        $('.ajaxproxy').AjaxProxy({
            dataType: "json",
            method: "post",
            formId: "content-add-form",
            formCheckHandler: function (form_id) {
                return common.formCheckHandler(form_id, true);
            },
            callbackDelay: __global.jdialog.timer,
            timeInterval: __global.jdialog.timer,
            callBack: function (data) {   /* 执行ajax之后的回调函数 */
                common.ajaxCallback(data);
            }
        });
        /**--tmpl-todo--**/

        /**-- deleteopt --**/
        $(".js-delete").click(function () {
            var id = $(this).attr('data-id');
            layer.confirm('确定要删除吗', ['确定', '取消'], function () {
                layer.load();
                $.post(exports.deleteUrl, {id: id}, function (data) {
                    layer.closeAll('loading');
                    if (data.code == 0 || data.code == 'success') {
                        layer.msg('删除成功');
                        document.location.reload();
                    } else {
                        layer.msg(data.message);
                    }
                }, 'json');
            });
        });
        $(".js-send-sms").click(function () {

            var accout = $("input[name='configs[sms_account]']").val();
            var password = $("input[name='configs[sms_password]']").val();
            var sign = $("input[name='configs[sms_sign]']").val();
            var provider = $("input[name='configs[sms_provider]']:checked").val();

            var test_content = $("input[name='test_content']").val();
            var test_mobile = $("input[name='test_mobile']").val();

            $.post('../../admin/remind/testSendSms', {
                provider: provider,
                accout: accout,
                password: password,
                sign: sign,
                test_content: test_content,
                test_mobile: test_mobile
            }, function (data) {
                layer.closeAll('loading');
                if (data.code == '000' || data.code == 'success') {
                    layer.msg('发送成功');
                } else {
                    layer.msg(data.message);
                }
            }, 'json');

        });

        $("input[name='configs[sms_open]']").on('change', function (i,e) {
            var value = $(this).is(":checked") ?  'on' : 0;
            $.post(exports.editUrl, {configs: {'sms_open': value}}, function (data) {
                if (data.code == "000") {
                    JDialog.tip.work({type: "ok", content: data.message, lock: true, timer: 500});
                } else {
                    JDialog.tip.work({type: "error", content: data.message, timer: 500});
                }
            }, 'json');

        });

        $(".js-edit").click(function () {
            id = $(this).attr('data-id');
            /**--tmpl-editlayer--**/
            $.get(exports.detailUrl, {id: id}, function (data) {

                var options = {
                    type: 1,
                    area: ['800px', '500px'],
                    content: JTemplate.render("editpanel", data),
                    btn: {
                        '确定': function () {
                            var form = $("#editpanel-form");
                            form.validate({
                                rules: {

                                    /**--tmpl-editrules--**/

                                },
                                messages: {
                                    /**--tmpl-editmessages--**/
                                },

                                submitHandler: function (form) {

                                    $(form).find('input[name=id]').remove();
                                    $(form).append("<input type='hidden' name='id' value='" + id + "' >");
                                    var data = $(form).serialize();
                                    common.ajaxResult(exports.editUrl, data);

                                }
                            });
                            form.submit();
                        },
                        "取消": function () {

                        }
                    }
                };
                var options = $.extend(__global.jdialog, options);
                var popWin = JDialog.win.work(options);

                /**--tmpl-edittodo--**/

            }, 'json');

        });
        /**--tmpl-othertodo--**/
        $('.js-qq-container').on('click', '#qq-add-btn', function () {
            var tmpl = $(this).closest('.input-group').clone();
            tmpl.find('button').removeAttr('id');
            tmpl.find('button span').removeClass('glyphicon-plus').addClass('glyphicon-minus');
            tmpl.find('button').addClass('js-qq-remove');
            tmpl.css('margin-top', '10px');
            tmpl.find('input').val('');

            if($('.js-qq-container').find('.input-group').length>=6){

               layer.msg('客服qq不能大于6个');
            }else{

                $(this).closest('.input-group').after(tmpl);

            }

        });
        $('.js-qq-container').on('click', '.js-qq-remove', function () {
            $(this).closest('.input-group').remove();
        });


        //-0--------------------------
        loadupload('files-upload','drop-area','src',function(data){$('input[name="configs[site_logo]"]').val(data.message);});
        loadupload('files-upload2','drop-area2','src2',function(data){$('input[name="configs[wx_qr]"]').val(data.message);});
        loadupload('files-upload3','drop-area3','src3',function(data){$('input[name="configs[site_logo2]"]').val(data.message);});

        function loadupload(filesUploadId,dropAreaId,formInputName,callbak) {

            var filesUpload = $('#'+filesUploadId);
            if (filesUpload) {

                var fileInput = filesUpload.css({height: 0, width: 0, 'overflow': 'hidden'});

                filesUpload.bind("change",function(){
                    traverseFiles(this.files,filesUploadId,dropAreaId,formInputName,callbak);
                });

                $('#'+dropAreaId).click(function () {
                    fileInput.click();
                }).show();
            }
        }


        function traverseFiles(files,filesUploadId,dropAreaId,formInputName,callbak) {
            if (typeof files !== "undefined") {

                file = files[0];
                uploadFile(files[0],filesUploadId,dropAreaId,formInputName,callbak);

            } else {
                fileList.innerHTML = "No support for the File API in this web browser";
            }
        }

        function uploadFile(file,filesUploadId,dropAreaId,formInputName,callback) {

            var img = document.createElement("img");
            var reader = new FileReader();

            if (typeof FileReader !== "undefined" && (/image/i).test(file.type)) {
                var size = document.getElementById(filesUploadId).files[0].size;


                reader.onload = (function (theImg) {
                    var fd = new FormData();

                    fd.append(formInputName,document.getElementById(filesUploadId).files[0]);

                    exports.ajaxResultByYu(
                        '/admin/upload/upload?fileInputName='+formInputName,
                        fd,
                        function (data) {
                            callback(data);
                        });
                    theImg.onload = function () {
                        if (size > 1024 * 1024) {
                            /*if ($("#drop-area-do-updoad").length > 0) {
                                $("#drop-area-do-updoad").val('true');
                                //$("#content-add-form").validate().element("#drop-area-do-updoad");
                            }
                            else {
                                layer.msg("图片大小不能超过1M");
                                return;
                            }*/

                        } else {

                            //$("#drop-area-do-updoad").val('');
                            //$("#content-add-form").validate()/* 07.30 .element("#drop-area-do-updoad")*/;

                        }
                        $("#"+dropAreaId).html(img);
                        $('#'+dropAreaId).imagefit({
                            mode: 'outside',
                            force: 'false',
                            halign: 'center',
                            valign: 'middle'
                        });
                    }
                    return function (evt) {
                        theImg.src = evt.target.result;
                    };
                }(img));

                reader.readAsDataURL(file);
            }
        }

        //-0--------------------------



    };


    /**--tmpl-otherfunction--**/
});
